How to make std::vector's operator[] compile doing bounds checking in DEBUG but not in RELEASE

Posted by Edison Gustavo Muenz on Stack Overflow See other posts from Stack Overflow or by Edison Gustavo Muenz
Published on 2009-08-17T20:57:18Z Indexed on 2010/04/17 3:23 UTC
Read the original article Hit count: 269

I'm using Visual Studio 2008.

I'm aware that std::vector has bounds checking with the at() function and has undefined behaviour if you try to access something using the operator [] incorrectly (out of range).

I'm curious if it's possible to compile my program with the bounds checking. This way the operator[] would use the at() function and throw a std::out_of_range whenever something is out of bounds.

The release mode would be compiled without bounds checking for operator[], so the performance doesn't degrade.

I came into thinking about this because I'm migrating an app that was written using Borland C++ to Visual Studio and in a small part of the code I have this (with i=0, j=1):

v[i][j]; //v is a std::vector<std::vector<int> >

The size of the vector 'v' is [0][1] (so element 0 of the vector has only one element). This is undefined behaviour, I know, but Borland is returning 0 here, VS is crashing. I like the crash better than returning 0, so if I can get more 'crashes' by the std::out_of_range exception being thrown, the migration would be completed faster (so it would expose more bugs that Borland was hiding).

© Stack Overflow or respective owner

Related posts about c++

Related posts about visual-studio-2008